/**
  **********************************************************************************
  * @file   : Service_Operation.cpp
  * @brief  : Operation support file.This file provides access ports to Operation.
  **********************************************************************************
  *  
**/
/* Includes ------------------------------------------------------------------*/
#include "Service_Operation.h"
#include "System_Config.h"
#include "Service_Communication.h"

#include "chassis_operation.h"
#include "pan_tilt_operation.h"
#include "shoot_operation.h"

/* Private define ------------------------------------------------------------*/
TaskHandle_t Operation_Handle;

/* Private variables ---------------------------------------------------------*/
E_CtrlMode CtrlMode; //控制模式
bool GyroscopeMode;  //小陀螺模式使能

/* Private function declarations ---------------------------------------------*/
void Task_Operation(void *arg);

/* Function prototypes -------------------------------------------------------*/
/**
* @brief  Initialize Operation service based on Upper Monitor.
*/
void Service_Operation_Init(void)
{
    xTaskCreate(Task_Operation,          /* Task function. */
                "Operation_Service",     /* Task Name. */
                Normal_Stack_Size,   /* Stack depth. */
                NULL,                /* Task parameter */
                PriorityBelowNormal, /* Priority */
                &Operation_Handle);      /* Task handle */
}

DR16_Classdef DR16;

#define USART1_RX_BUFFER_SIZE 64
uint8_t Uart1_Rx_Buff[USART1_RX_BUFFER_SIZE];

uint32_t DR16_call_back(uint8_t *buf, uint16_t len)
{
    DR16.DataCapture((DR16_DataPack_Typedef *)buf);
    return 0;
}

void DR16_Uart_Init(void)
{
    Uart_Init(&huart1, Uart1_Rx_Buff, USART1_RX_BUFFER_SIZE, DR16_call_back);
}

/**
* @brief  下发操作指令的线程
* @param  None.
* @return None.
*/
void Task_Operation(void *arg)
{
    for (;;)
    {
        static uint16_t prescale = 0;
        if (prescale++ >= 10)
        {
            prescale = 0;

        }
        DR16.Check_Link(xTaskGetTickCount());
        LinkageStatus_Typedef DR16_status = DR16.GetStatus();

        if (DR16_status == Connection_Established) // 遥控器连接
        {
            // 左侧开关决定控制模式
            if (DR16.GetSW_L() == SW_MID)
                CtrlMode = REMOTE_CONTROL;
            else if (DR16.GetSW_L() == SW_UP)
                CtrlMode = KEYBOARD_CONTROL;
            else
                CtrlMode = DISABLE_CONTROL;

            // 键盘控制模式下，开启小陀螺模式
            if (CtrlMode == KEYBOARD_CONTROL)
                GyroscopeMode = true;
            else
                GyroscopeMode = false;
        }
        else    // 遥控器离线
        {
            CtrlMode = DISABLE_CONTROL;
        }

        chassis_operation();
        pan_tilt_operation();
        shoot_operation();

        vTaskDelay(1); // Pass to next ready task
    }
}

/************************ COPYRIGHT(C) USTC-ROBOWALKER **************************/
